﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace HY.Utility.Enum
{
    public static class EnumAttributeHelper
    {
        public static IEnumerable<string> GetEnumDescription(Type t) 
        {
            List<string> tlist = new List<string>();
            foreach (var v in System.Enum.GetValues(t))
            {
                var attrs = Attribute.GetCustomAttributes(v.GetType().GetField(v.ToString()), false);
                if (attrs != null && attrs.Length > 0)
                {
                    DescriptionAttribute descattr = attrs[0] as DescriptionAttribute;
                    if (descattr != null)
                        tlist.Add(descattr.Description);
                }
            }
            return tlist;
        }

        public static string GetEnumDescription(this System.Enum that)
        {
            var output = "";
            var attrs = Attribute.GetCustomAttributes(that.GetType().GetField(that.ToString()), false);
            if (attrs != null && attrs.Length > 0)
            {
                DescriptionAttribute descattr = attrs[0] as DescriptionAttribute;
                if (descattr != null)
                    output = descattr.Description;
            }
            return output;
        }


        public static T GetEnumValueFromDescription<T>(string desc)
        {
            Type t = typeof(T);
            foreach (var v in System.Enum.GetValues(t))
            {
                var attrs = Attribute.GetCustomAttributes(v.GetType().GetField(v.ToString()), false);
                if (attrs != null && attrs.Length > 0)
                {
                    DescriptionAttribute descattr = attrs[0] as DescriptionAttribute;
                    if (descattr != null)
                        if (descattr.Description == desc)
                            return (T)v;
                }
            }
            return default(T);
        }

        //public static string GetEnumDescription(System.Enum v)
        //{
        //    var descption = "";
        //    var field = v.GetType().GetField(v.ToString());
        //    var attr = (field.GetCustomAttributes(typeof(DescriptionAttribute), false)) as DescriptionAttribute[];
        //    if (attr != null && attr.Length > 0)
        //        descption = attr[0].Description;
        //    return descption;
        //}
    }
}
